package cn.yanhu.kuwanapp

import android.app.Application
import android.graphics.Bitmap
import android.os.Build
import cn.woochen.comlib.config.RetrofitUtil
import cn.woochen.comlib.util.ConfigPref
import cn.woochen.comlib.util.PackageUtil
import cn.yanhu.kuwanapp.http.UrlConstainer
import cn.yanhu.kuwanapp.http.factory.CustomizeGsonConverterFactory
import cn.yanhu.kuwanapp.http.https.CertificateManageHelper
import cn.yanhu.kuwanapp.http.intercept.UrlInterceptor
import cn.yanhu.kuwanapp.kefu.QYUicustomization
import cn.yanhu.kuwanapp.utils.Config
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.helper.MiitHelper
import cn.yanhu.kuwanapp.utils.helper.ToastDarkStyle
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import cn.yanhu.kuwanapp.welfare.ad.csj.TTAdManagerHolder
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.hjq.toast.ToastUtils
import com.qiyukf.unicorn.api.*
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tendcloud.tenddata.TCAgent
import com.yilan.sdk.ui.YLUIInit
import jfq.wowan.com.myapplication.PlayMeUtil


class AppApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        if (PackageUtil.isMainProcess(this)) {
            initRetrofit()
            initToast()
            configRefresh()
            ThirdAccountHelper.init(this)
            initAd()
            initCplSdk()
            initVideoSdk()
            initSdk()
        }
    }

     fun initSdk(){
      if (isAgreePrivacy){
          initOaid()
          intTCA()
          initService()
      }
    }

    /**
     * thinkdata初始化
     *
     */
    private fun intTCA() {
        TCAgent.LOG_ON = UrlConstainer.SHOW_LOG
        TCAgent.init(this)
        TCAgent.setReportUncaughtExceptions(true)
    }

    /**
     * 七鱼客服初始化
     */
    private fun initService() {
        val options = YSFOptions()
        options.uiCustomization = QYUicustomization()
        options.uiCustomization.isShowTitleAvatar = true
        options.uiCustomization.titleCenter = true
        options.statusBarNotificationConfig = StatusBarNotificationConfig()
        Unicorn.init(this, Config.QY_KEY, options, object : UnicornImageLoader {
            override fun loadImageSync(p0: String?, p1: Int, p2: Int): Bitmap? {
                return null
            }

            override fun loadImage(
                uri: String?, width: Int, height: Int,
                p3: ImageLoaderListener?
            ) {
                var finalHeight = height
                var finalWidth = width
                if (width <= 0 || height <= 0) {
                    finalHeight = Int.MIN_VALUE
                    finalWidth = height
                }

                val options = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
                Glide.with(applicationContext).asBitmap().load(uri).apply(options).into(object :
                    SimpleTarget<Bitmap?>(finalWidth, finalHeight) {

                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap?>?
                    ) {
                        /* if (listener != null) {
                            listener.onLoadComplete(resource)
                        }*/
                    }
                })
            }
        })
    }

    /**
     * vaas初始化
     */
    private fun initVideoSdk() {
        YLUIInit.getInstance()
            .setApplication(this)
            .setAccessKey(Config.VIDEO_ACCESS_KEY)//设置accesskey
            .setAccessToken(Config.VIDEO_ACCESS_TOKEN)//设置token
//            .setSID() //设置渠道号，用于分渠道广告屏蔽
            .logEnable(UrlConstainer.SHOW_LOG)//日志开关，默认关闭
            .aaid(mDeviceAaid)//如工程中集成了“移动安全联盟”，请配置相关id
            .oaid(mDeviceOaid)//如工程中集成了“移动安全联盟”，请配置相关id
            .vaid(mDeviceVaid)//如工程中集成了“移动安全联盟”，请配置相关id
            .build()
    }

    /**
     * 初始化sdk
     */
    private fun initCplSdk() {
        PlayMeUtil.init(this, "${packageName}.fileprovider", true, true)
    }

    /**
     * 初始化广告
     */
    private fun initAd() {
        TTAdManagerHolder.init(this)
    }

    private var mDeviceOaid by ConfigPref(Constants.DEVICE_OAID, "")
    private var mDeviceVaid by ConfigPref(Constants.DEVICE_VAID, "")
    private var mDeviceAaid by ConfigPref(Constants.DEVICE_AAID, "")
    private var isAgreePrivacy by ConfigPref(Constants.IS_AGREE_PRIVACY, false)

    /**
     * 获取oaid
     */
    private fun initOaid() {
        try {
            MiitHelper(object : MiitHelper.AppIdsUpdater {
                override fun OnIdsAvalid(isSupport: Boolean, oaid: String, vaid: String, aaid: String) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                        if (isSupport) {
                            mDeviceOaid = oaid
                            mDeviceVaid = vaid
                            mDeviceAaid = aaid
                        } else {
                            //showToast("暂不支持当前设备!")
                        }
                    } else {
                        mDeviceOaid = oaid
                        mDeviceVaid = vaid
                        mDeviceAaid = aaid
                    }
                }
            }).callFromReflect(this)
        } catch (e: Exception) {

        }
    }

    /**
     * 初始化toast工具类
     */
    private fun initToast() {
        ToastUtils.init(this, ToastDarkStyle())
    }

    /**
     * 配置刷新样式
     */
    private fun configRefresh() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white)
                .setHeaderHeight(50f)
            ClassicsHeader(context).setEnableLastTime(true)
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            layout.setEnableAutoLoadMore(true)
            ClassicsFooter(context).setDrawableSize(20f).setTextSizeTitle(12f)
        }
    }

    /**
     * 初始化网络请求
     */
    private fun initRetrofit() {
        //配置服务器地址
        UrlConstainer.getServerAddress()
        //retrofit初始化
        val instance = RetrofitUtil.getInstance()
        instance.timeout(5L).debugMode(UrlConstainer.SHOW_LOG).proxy(UrlConstainer.canProxy)
            .interceptor(UrlInterceptor()).converterFactory(CustomizeGsonConverterFactory.create())
        instance.init(UrlConstainer.appBaseUrl, {
            if (UrlConstainer.SHOW_LOG) {
                it.sslSocketFactory(
                    CertificateManageHelper.getSSLSocketFactory(),
                    CertificateManageHelper.getTrustManager()
                )
                it.hostnameVerifier(CertificateManageHelper.getHostnameVerifier())
            }
        })
    }
}